import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Tooltip, Popconfirm, message, Spin, Button, Icon, Modal, notification, Radio } from 'antd'
import invoiceBagApproveService from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve.service'
import CreateInvoice from 'containers/my-account/create-invoice'
import Invoice from 'containers/my-account/invoice'
import SlideFrame from 'components/slide-frame'
import ScanSnap from 'components/scan-snap'
import baseService from "share/base.service";
import { setDocumentaryCompany } from "actions/login";
import ResizeTable from 'components/resize-table'

class InvoiceList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [{
        dataIndex: 'index', title: messages('financial-management.key403')/*序号*/,
        render: (text, record, index) => index + 1,
        width: 50
      }, {
        dataIndex: 'type', title: messages('common.invoice.type')/*发票类型*/, width: 200,
        render: text => <div className='bad-table-cell' style={{ width: 184 }}>
          <Tooltip title={text} placement='topLeft'>{text}</Tooltip>
        </div>,
        sorter: (a, b) => a.type > b.type ? 1 : -1
      }, {
        dataIndex: 'billingCode', title: messages('financial-management.key611')/*发票代码*/, width: 200,
        render: text => <Tooltip title={text} placement='topLeft'>{text || '-'}</Tooltip>,
        sorter: (a, b) => a.billingCode > b.billingCode ? 1 : -1
      }, {
        dataIndex: 'billingNo', title: messages('financial-management.key612')/*发票号码*/, width: 100,
        render: text => <div className='bad-table-cell' style={{ width: 84 }}>
          <Tooltip title={text} placement='topLeft'>{text || '-'}</Tooltip>
        </div>,
        sorter: (a, b) => a.billingNo > b.billingNo ? 1 : -1
      }, {
        dataIndex: 'billingTime', title: messages('financial-management.key613')/*开票日期*/, width: 100,
        render: billingTime => billingTime ? new Date(billingTime * 1000).format('yyyy-MM-dd') : '-',
        sorter: (a, b) => a.billingTime - b.billingTime
      }, {
        dataIndex: 'vatInvoiceCurrencyCode', title: messages('financial-management.key405')/*币种*/, width: 50,
        render: text => <Tooltip title={text} placement='topLeft'>{text}</Tooltip>
      }, {
        dataIndex: 'feeWithoutTax', title: messages('financial-management.key614')/*金额合计*/, width: 100,
        render: (feeWithoutTax, record) => feeWithoutTax === null ?
          <span className='money-cell'>-</span> :
          this.filterMoney((feeWithoutTax / 100), queryCurrencyPrecision(record.vatInvoiceCurrencyCode))
      }, {
        dataIndex: 'taxRate', title: messages('financial-management.key747')/*税率*/, width: 100,
        render: taxRate => taxRate === null ?
          '-' :
          `${taxRate * 100}%`
      }, {
        dataIndex: 'tax', title: messages('common.tax')/*税额*/, width: 100,
        render: (tax, record) => tax === null ?
          <span className='money-cell'>-</span> :
          this.filterMoney((tax || 0) / 100, queryCurrencyPrecision(record.vatInvoiceCurrencyCode))
      }, {
        dataIndex: 'fee', title: messages('financial-management.key616')/*价税合计*/, width: 100,
        render: (fee, record) => this.filterMoney(
          fee / 100,
          queryCurrencyPrecision(record.vatInvoiceCurrencyCode)
        ),
        sorter: (a, b) => a.fee - b.fee
      }, {
        dataIndex: 'invoiceGoods', title: messages('financial-management.key748')/*发票商品服务名称*/,
        width: 200,
        render: invoiceGoods => {
          let text = invoiceGoods.map(goods => goods.goodsName).join('、') || '-';
          return <div className='bad-table-cell' style={{ width: 184 }}>
            <Tooltip
              title={text}
              overlayStyle={{ width: 200,  whiteSpace: 'pre-wrap' }}
              placement='topLeft'
            >{text}</Tooltip>
          </div>
        }
      }, {
        dataIndex: 'slicingAttachment', title: messages('common.attachments')/*附件*/, width: 50,
        className: 'attachment-col',
        render: slicingAttachment => slicingAttachment ?
          <Tooltip
            placement='leftTop'
            overlayClassName='invoice-list-tooltip'
            getPopupContainer={triggerNode => triggerNode.parentNode}
            autoAdjustOverflow={false}
            title={<img src={slicingAttachment.fileURL} style={{ width: 400 }} alt=''/>}
          >
            <a>1</a>
          </Tooltip> : '-'
      }, {
        dataIndex: 'id', title: messages('financial-management.key254')/*操作*/,  width: 100,
        render: this.renderOperationColumns
      }],
      loading: false,
      loadingInvoice: null,
      showEditInvoiceFlag: false,
      nowInvoice: null,
      invoiceUserFp: {},
      currencyList: [],
      showViewInvoiceFlag: false,
      applicantOID: null,
      nowCreateInvoice: null,
      showCreateInvoiceFlag: false,
      unexpandedList: [],
      checking: false,
      checkTag: 'all'
    }
  }

  renderOperationColumns = (id, record) => {
    const { invoiceList, readOnly, approved } = this.props;
    const { auditReceiptIds = [] } = invoiceList;
    let isFinance = record.isFinance;
    let editOperation = (
      <a onClick={() => this.handleEditInvoice(record, isFinance)}>
        {messages('financial-management.key500')/*编辑*/}
      </a>
    );
    let viewOperation = (
      <a onClick={() => this.handleViewInvoice(id)}>
        {messages('common.view')/*查看*/}
      </a>
    );
    return id === this.state.loadingInvoice ? <Spin/> : (
      (isFinance ? (readOnly || approved) : (readOnly || (!auditReceiptIds || auditReceiptIds.indexOf(id) === -1))) ? (
        viewOperation
      ) : (
        <span>
          <Popconfirm
            title={messages('financial-management.key749')/*你确定要删除这张发票吗？*/}
            onConfirm={() => this.handleDeleteInvoice(id)}
          >
            <a>{messages('financial-management.key501')/*删除*/}</a>
          </Popconfirm>
          <span className="ant-divider"/>
          {(record.checkResult === 'R_0000' || record.alipayOrWeChat) ? viewOperation : editOperation}
        </span>
      )
    )
  };

  componentDidMount(){
    const { baseInfo } = this.props;
    if(baseInfo.userOID) {
      this.setState({ loading: true });
      Promise.all([
        baseService.getAllCurrencyByLanguage('zh_cn', baseInfo.userOID, true),
        baseService.getFpByUserOID(baseInfo.userOID)
      ]).then(res => {
        this.setState({
          loading: false,
          currencyList: res[0].data,
          invoiceUserFp: res[1].data
        })
      });
    }
    const { columns } = this.state;
    this.setState({ columns: this.wrapCheckClassName(columns) });
  }

  wrapCheckClassName = columns => {
    return columns.map(column => {
      let sourceRender = column.render;
      column.render = (value, record, index) => (
        <span className={this.classNames({
          'not-matched-columns':
            record.notMatchedColumns &&
            record.notMatchedColumns.indexOf(column.dataIndex) > -1
        })}>
          {sourceRender(value, record, index)}
        </span>
      );
      return column;
    })
  };

  handleViewInvoice = id => {
    if(this.state.loadingInvoice) {
      message.error(messages('financial-management.key750')/*请等待*/);
      return ;
    }
    this.setState({ loadingInvoice: id });
    invoiceBagApproveService.getInvoiceDetail(id).then(res => {
      this.setState({ nowInvoice: res.data }, () => {
        this.setState({ showViewInvoiceFlag: true, loadingInvoice: null })
      });
    });
  };

  handleDeleteInvoice = id => {
    this.setState({ loading: true });
    invoiceBagApproveService.deleteInvoice(id).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.props.onRefreshInvoice();
      this.setState({ loading: false });
    }).catch(() => {
      this.setState({ loading: false });
    });
  };

  handleEditInvoice = (record, isFinance) => {
    if(this.state.loadingInvoice) {
      message.error(messages('financial-management.key750')/*请等待*/);
      return ;
    }
    this.setState({ loadingInvoice: record.id });
    Promise.all([
      invoiceBagApproveService.getInvoiceDetail(record.id),
      baseService.getCompanyByUserOID(record.applicantOID)
    ]).then(res => {
      this.props.dispatch(setDocumentaryCompany(res[1].data));
      if(isFinance) {
        this.setState({ nowCreateInvoice: res[0].data, applicantOID: record.applicantOID }, () => {
          this.setState({ showCreateInvoiceFlag: true, loadingInvoice: null })
        });
      } else {
        this.setState({ nowInvoice: res[0].data, applicantOID: record.applicantOID }, () => {
          this.setState({ showEditInvoiceFlag: true, loadingInvoice: null })
        });
      }
    });
  };

  getAmount = (data, rate = 100) => {
    if(!data)
      return `${this.props.company.baseCurrency} 0.00`;
    if(data.length === 0) {
      return '0.00';
    } else {
      let map = {};
      data.map(item => {
        Object.keys(item).map(key => {
          map[key] = item[key];
        })
      });
      return Object.keys(map)
        .map(c => `${c} ${this.filterMoney(map[c] / rate, queryCurrencyPrecision(c), true)}`)
        .join(' , ')
    }
  };

  handleCloseEditInvoice = () => {
    this.setState({ showEditInvoiceFlag: false, nowInvoice: null, applicantOID: null })
  };

  onSaveInvoice = () => {
    this.setState({ showEditInvoiceFlag: false });
    this.props.onRefreshInvoice();
  };

  onCreateInvoice = () => {
    this.setState({ showCreateInvoiceFlag: false, nowCreateInvoice: null });
    this.props.onRefreshInvoice();
  };

  handleCloseCreateInvoice = () => {
    this.setState({ showCreateInvoiceFlag: false, nowCreateInvoice: null });
  };

  getExpandedRender = record => {
    if(record.receiptLabels) {
      return record.receiptLabels
        .filter(item => item.type !== 'INSP_SUCCEEDED')
        .map(item => item.name)
        .join(',')
    } else {
      return null;
    }
  };

  renderClass = record => {
    let result = '';
    result += record.receiptLabels && record.receiptLabels
      .filter(item => item.type !== 'INSP_SUCCEEDED').length > 0 ? '' : 'row-expand-display-none';
    if(record.checkTag === 'NOT_MATCHED')
      result += ' error-table-line';
    if(record.checkTag === 'TO_BE_CHECKED')
      result += ' warn-table-line';
    // if(record.invoiceTypeNo)
    //   result += ' error-table-line';
    // if(record.checkResult !== 'R_0000' && !record.alipayOrWeChat)
    //   result += ' warn-table-line';
    return result
  };

  handleClickInfo = () => {
    Modal.info({
      title: messages('financial-management.key414')/*说明*/,
      content: (
        <div>
          <p>
            {messages('financial-management.key777')
              /*1.【扫描发票】：请购买富士通iX500型号扫描仪，用于批量扫描发票。
              建议统一大小和材质的发票在一批扫，不同大小发票一起扫描容易卡纸。*/}
          </p>
          <p>
            {messages('financial-management.key778')
              /*2.【扫描发票】：若按钮为禁用则表示没有连接扫描仪或当前系统不支持
              （目前仅支持安装了仪器驱动的windows系统，请保持系统端口8089为仪器所用），连接成功后请刷新页面。*/}
          </p>
          <p>
            {messages('financial-management.key779')
              /*3.【财务扫描发票】：本页面【扫描发票】、【录入发票】来源的发票；可编辑、删除发票。*/}
          </p>
          <p>
            {messages('financial-management.key780')
              /*4.【需贴票发票】：员工录入的，没有【免贴票】标签的发票。*/}
          </p>
          <p>
            {messages('financial-management.key781')
              /*5.【免贴票发票】：员工录入的，有【免贴票】标签的发票；可查看发票。*/}
          </p>
        </div>
      )
    });
  };

  handleScan = base64 => {
    const key = `open${Date.now()}`;
    const { invoiceBagId } = this.props;
    notification.open({
      key,
      message: messages('financial-management.key782')/*识别中...*/,
      icon: <Icon type="loading" />,
      duration: null
    });
    invoiceBagApproveService.scanBase64(base64, invoiceBagId).then(res => {
      if(res.data.success) {
        let method = 'info';
        switch(res.data.code) {
          case 130113:
            method = 'success';
            break;
          case 130114:
            method = 'warning';
            break;
          case 130115:
            method = 'error';
            break;
        }
        this.props.onRefreshInvoice();
        notification.close(key);
        notification[method]({
          message: res.data.message,
          duration: 4
        });
      }
    }).catch(() => {
      notification.close(key);
    })
  };

  onExpand = (expanded, record) => {
    const { unexpandedList } = this.state;
    if(expanded) {
      unexpandedList.delete(record.id);
    } else {
      unexpandedList.push(record.id);
    }
    this.setState({ unexpandedList });
  };

  sortFinanceInvoice = (a, b) => a.invoiceTypeNo && !b.invoiceTypeNo ? -1 : 0;

  checkInvoice = () => {
    this.setState({ checking: true });
    const { invoiceBagId, onRefreshInvoice } = this.props;
    invoiceBagApproveService.checkInvoices(invoiceBagId)
      .then(res => {
        message.success(messages('financial-management.key897')/*核对完成*/);
        onRefreshInvoice();
      })
      .finally(() => {
        this.setState({ checking: false })
      })
  };

  onChangeCheckTag = e => {
    let checkTag = e.target.value;
    this.setState({ checkTag });
  };

  filterCheckTag = record => {
    const { checkTag } = this.state;
    return checkTag === 'all' || record.checkTag === checkTag;
  };

  render() {
    const {
      columns, loading, unexpandedList, checking,
      nowInvoice, showEditInvoiceFlag, showViewInvoiceFlag,
      showCreateInvoiceFlag, nowCreateInvoice, checkTag,
      invoiceUserFp, currencyList, applicantOID
    } = this.state;
    const { invoiceList, invoiceLoading, baseInfo, invoiceBagId, approved, company, showOCRFlag } = this.props;
    return (
      <div>
        {!approved && (
          <div className="invoice-list-head">
            <Radio.Group onChange={this.onChangeCheckTag} value={checkTag}>
              <Radio.Button value="all">{messages('common.all')/*全部*/}</Radio.Button>
              <Radio.Button value="NOT_MATCHED" className='error-table-line'>{messages('financial-management.key898')/*未匹配*/}</Radio.Button>
              <Radio.Button value="TO_BE_CHECKED" className='warn-table-line'>{messages('financial-management.key899')/*待核对*/}</Radio.Button>
              <Radio.Button value="CHECKED">{messages('financial-management.key213')/*已核对*/}</Radio.Button>
            </Radio.Group>
            <div className="button-area">
              {showOCRFlag && (
                <span>
                  <ScanSnap
                    buttonProps={{ type: 'primary' }}
                    onScan={this.handleScan}
                  >
                    {messages('financial-management.key783')/*扫描发票*/}
                  </ScanSnap>
                  <Icon type="info-circle" onClick={this.handleClickInfo} className='scan-info'/>
                </span>
              )}
              <Button
                className='button-area-create'
                onClick={() => this.setState(
                  { nowCreateInvoice: {} },
                  () => { this.setState({ showCreateInvoiceFlag: true }) })
                }
              >
                {messages('financial-management.key784')/*录入发票*/}
              </Button>
              <Button onClick={this.checkInvoice} loading={checking}>
                {messages('financial-management.key900')/*核对发票*/}
              </Button>
            </div>
          </div>
        )}
        <div className="table-count">
          <b style={{ marginRight: 10 }}>{messages('financial-management.key785')/*财务扫描*/}</b>
          {messages('financial-management.key752')/*发票数量*/}：
          <b className="number">{invoiceList.financeReceipts.length}</b>
          <span className="ant-divider"/>
          {messages('financial-management.key753')/*总计*/}：
          <b className="number">{this.getAmount(invoiceList.financeReceiptStatistics, 1)}</b>
        </div>
        <ResizeTable
          columns={columns}
          bordered
          expandedRowRender={this.getExpandedRender}
          pagination={false}
          rowKey="id"
          rowClassName={this.renderClass}
          scroll={{ x: true }}
          dataSource={invoiceList.financeReceipts.sort(this.sortFinanceInvoice).filter(this.filterCheckTag)}
          loading={loading || invoiceLoading}
          size="middle"
          onExpand={this.onExpand}
          expandedRowKeys={
            invoiceList.financeReceipts
              .map(r => r.id)
              .filter(id => unexpandedList.indexOf(id) === -1)
          }
        />

        <div className="table-count" style={{ marginTop: 30 }}>
          <b style={{ marginRight: 10 }}>{messages('financial-management.key751')/*员工录入（需贴票）*/}</b>
          {messages('financial-management.key752')/*发票数量*/}：
          <b className="number">{invoiceList.withReceipt.length}</b>
          <span className="ant-divider"/>
          {messages('financial-management.key753')/*总计*/}：
          <b className="number">{this.getAmount(invoiceList.withReceiptStatistics)}</b>
        </div>
        <ResizeTable
          columns={columns}
          bordered
          expandedRowRender={this.getExpandedRender}
          loading={loading || invoiceLoading}
          pagination={false}
          rowKey="id"
          rowClassName={this.renderClass}
          scroll={{ x: true }}
          dataSource={invoiceList.withReceipt.filter(this.filterCheckTag)}
          size="middle"
          onExpand={this.onExpand}
          expandedRowKeys={
            invoiceList.withReceipt
              .map(r => r.id)
              .filter(id => unexpandedList.indexOf(id) === -1)
          }
        />
        <div className="table-count" style={{ marginTop: 30 }}>
          <b style={{ marginRight: 10 }}>{messages('financial-management.key754')/*员工录入（免贴票）*/}</b>
          {messages('financial-management.key752')/*发票数量*/}：
          <b className="number">{invoiceList.freeReceipt.length}</b>
          <span className="ant-divider"/>
          {messages('financial-management.key753')/*总计*/}：
          <b className="number">{this.getAmount(invoiceList.freeReceiptStatistics)}</b>
        </div>
        <ResizeTable
          columns={columns}
          bordered
          expandedRowRender={this.getExpandedRender}
          loading={loading || invoiceLoading}
          pagination={false}
          rowKey="id"
          rowClassName={this.renderClass}
          scroll={{ x: true }}
          dataSource={invoiceList.freeReceipt.filter(this.filterCheckTag)}
          size="middle"
          onExpand={this.onExpand}
          expandedRowKeys={
            invoiceList.freeReceipt
              .map(r => r.id)
              .filter(id => unexpandedList.indexOf(id) === -1)
          }
        />
        {nowCreateInvoice && (
          <SlideFrame
            content={CreateInvoice}
            show={showCreateInvoiceFlag}
            hasFooter={false}
            params={{
              userOID: baseInfo.userOID,
              receipt: nowCreateInvoice,
              invoiceUserFp,
              currencyList,
              createType: 2,
              receiptOperateScene: 3,
              onCreate: this.onCreateInvoice,
              receiptList: [],
              onBack: () => this.setState({ showCreateInvoiceFlag: false }),
              invoiceBagId,
              currency: nowCreateInvoice.vatInvoiceCurrencyCode || company.baseCurrency
            }}
            onClose={() => this.setState({ showCreateInvoiceFlag: false })}
            afterClose={this.handleCloseCreateInvoice}
            title={messages('financial-management.key784')/*录入发票*/}
          />
        )}
        {nowInvoice && (
          <SlideFrame
            content={CreateInvoice}
            show={showEditInvoiceFlag}
            hasFooter={false}
            params={{
              userOID: applicantOID,
              receipt: nowInvoice,
              invoiceUserFp,
              currencyList,
              createType: 2,
              receiptOperateScene: 3,
              invoiceOID: nowInvoice ? nowInvoice.invoiceOID : null,
              onCreate: this.onSaveInvoice,
              receiptList: [],
              onBack: () => this.setState({ showEditInvoiceFlag: false }),
              currency: nowInvoice.vatInvoiceCurrencyCode || company.baseCurrency
            }}
            onClose={() => this.setState({ showEditInvoiceFlag: false })}
            afterClose={this.handleCloseEditInvoice}
            title={messages('financial-management.key755')/*编辑发票*/}
          />
        )}
        {nowInvoice && (
          <SlideFrame
            content={Invoice}
            show={showViewInvoiceFlag}
            hasFooter={false}
            params={{
              invoiceList: [nowInvoice],
              disabledEdit: true,
              onBack: () => this.setState({ showEditInvoiceFlag: false })
            }}
            afterClose={this.toState({nowInvoice: null})}
            onClose={() => this.setState({ showViewInvoiceFlag: false })}
            title={messages('financial-management.key756')/*查看发票*/}
          />
        )}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(InvoiceList)
